package springmvc.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.Data;

import org.dhbw.cocktail.Cocktail;
import org.dhbw.cocktail.Ingredient;
import org.dhbw.cocktail.mixer.ICocktailMixer;
import org.dhbw.cocktail.mixer.MixerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
 * Controller to search for cocktails and ingredients
 * 
 * @author Roland von Werden
 */
@Data
public class SearchController implements Controller {

	@Autowired
	@Qualifier("cocktail_mixer_factory")
	MixerFactory mixerFactory;

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse arg1) throws Exception {
		ModelAndView mav = new ModelAndView();
		// retrieve searchstring
		String serachterm = request.getParameter("q");
		// if the searchstring is not null, search for the string
		// get ICocktailMixer instance
		ICocktailMixer cocktailMixer = mixerFactory.getCocktailMixer();
		if (serachterm != null) {
			List<Cocktail> cocktails = null;
			// search for the cocktail
			cocktails = cocktailMixer.searchCocktail(serachterm);
			mav.addObject("cocktails", cocktails);
			List<Ingredient> ingredients = null;
			// search for the ingredients
			ingredients = cocktailMixer.searchIngredient(serachterm);
			mav.addObject("ingredients", ingredients);
		} else {

			List<Cocktail> cocktails = null;
			// search for the cocktail
			cocktails = cocktailMixer.getAllCocktails();
			mav.addObject("cocktails", cocktails);
		}
		return mav;
	}

}
